package org.jf.tool.fx.jftoolfx.encrypt.controller;

import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.layout.HBox;
import javafx.stage.FileChooser;
import org.jf.tool.fx.jftoolfx.common.BaseController;

import java.io.File;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

/**
 * @author jifeng_zhang
 * @date 2025/8/15 下午3:43
 */
public class Base64Controller extends BaseController {

    @FXML
    public HBox fileBox;
    @FXML
    public TextField filePathField;
    @FXML
    private TextArea plainText;
    @FXML
    private TextArea result;
    @FXML
    private ToggleGroup plainToggleGroup;
    @FXML
    private ToggleGroup resultToggleGroup;

    @Override
    protected void init(URL url, ResourceBundle resourceBundle) {

    }

    @FXML
    private void changeType() {
        String type = plainToggleGroup.getSelectedToggle().getUserData().toString();
        if ("plain".equals(type)) {
            fileBox.setVisible(false);
            fileBox.setManaged(false);
            plainText.setVisible(true);
            plainText.setManaged(true);
        } else if ("file".equals(type) || "img".equals(type)) {
            plainText.setVisible(false);
            plainText.setManaged(false);
            fileBox.setVisible(true);
            fileBox.setManaged(true);
        }
    }

    @FXML
    private void upload() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择要上传的文件");

        // 设置文件过滤器（可选）
        String type = plainToggleGroup.getSelectedToggle().getUserData().toString();
        FileChooser.ExtensionFilter filter;
        if ("img".equals(type)) {
            //限制图片格式
            filter = new FileChooser.ExtensionFilter("图片文件 (*.png, *.jpg, *.jpeg)", "*.png", "*.jpg", "*.jpeg");
        } else {
            filter = new FileChooser.ExtensionFilter("所有文件 (*.*)", "*.*");
        }
        fileChooser.getExtensionFilters().add(filter);
        // 设置初始目录为上次使用的目录
        if (LAST_DIRECTORY != null) {
            fileChooser.setInitialDirectory(LAST_DIRECTORY);
        } else {
            fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));
        }

        // 获取当前窗口
        File file = fileChooser.showOpenDialog(TOP_STAGE);
        if (file != null) {
            LAST_DIRECTORY = file.getParentFile();
            filePathField.setText(file.getAbsolutePath());
        } else {
            filePathField.setText("");
        }
    }

    @FXML
    private void encode() {
        try {
            String type = plainToggleGroup.getSelectedToggle().getUserData().toString();
            String resultType = resultToggleGroup.getSelectedToggle().getUserData().toString();
            String resultStr = "";
            if ("plain".equals(type)) {
                String plain = plainText.getText();
                if ("hex".equals(resultType)) {
                    resultStr = HexFormat.of().formatHex(Base64.getEncoder().encode(plain.getBytes(StandardCharsets.UTF_8))).toUpperCase();
                } else {
                    resultStr = Base64.getEncoder().encodeToString(plain.getBytes(StandardCharsets.UTF_8));
                }
            } else {
                File file = new File(filePathField.getText());
                if (file.exists()) {
                    byte[] fileData = Files.readAllBytes(Paths.get(file.getPath()));
                    if ("hex".equals(resultType)) {
                        resultStr = HexFormat.of().formatHex(Base64.getEncoder().encode(fileData)).toUpperCase();
                    } else {
                        resultStr = Base64.getEncoder().encodeToString(fileData);
                        if ("img".equals(type)) {
                            //获取文件后缀
                            String suffix = file.getName().substring(file.getName().lastIndexOf(".") + 1);
                            resultStr = "data:image/" + suffix + ";base64," + resultStr;
                        }
                    }
                } else {
                    resultStr = "请先上传文件！";
                }
            }
            result.setText(resultStr);
        } catch (Exception e) {
            throw new RuntimeException("MD5 algorithm not available", e);
        }
    }

    @FXML
    private void decode() {
        try {
            String plainType = plainToggleGroup.getSelectedToggle().getUserData().toString();
            String resultType = resultToggleGroup.getSelectedToggle().getUserData().toString();
            String resultStr = "";
            if ("plain".equals(plainType)) {
                String plain = plainText.getText();
                byte[] base64Decode = Base64.getDecoder().decode(plain);
                if ("hex".equals(resultType)) {
                    resultStr = HexFormat.of().formatHex(base64Decode).toUpperCase();
                } else {
                    resultStr = new String(base64Decode);
                }
            } else if ("file".equals(plainType)) {
                File file = new File(filePathField.getText());
                if (file.exists()) {
                    byte[] fileData = Files.readAllBytes(Paths.get(file.getPath()));
                    byte[] base64Decode = Base64.getDecoder().decode(fileData);
                    if ("hex".equals(resultType)) {
                        resultStr = HexFormat.of().formatHex(base64Decode).toUpperCase();
                    } else {
                        resultStr = new String(base64Decode);
                    }
                } else {
                    resultStr = "请先上传文件！";
                }
            }
            result.setText(resultStr);
        } catch (Exception e) {
            result.setText("解码失败：" + e.getMessage());
        }
    }

    @FXML
    private void clear() {
        plainText.setText("");
        result.setText("");
        filePathField.setText("");
    }

    @FXML
    private void copy(ActionEvent event) {
        copy(result.getText());
    }
}
